from django.forms import ModelForm
from django.shortcuts import render, redirect

from ManageApp.models import MyAdmin
from ManageApp.utils import page_nav,bootstrap
import hashlib
from django.conf import settings
# setting文件里有SECRET_KEY
from django import forms
from django.core.exceptions import ValidationError
from ManageApp.utils.bootstrap import BootstrapForm


def get_md5(data):
    obj = hashlib.md5(settings.SECRET_KEY.encode("utf-8"))
    obj.update(data.encode("utf-8"))
    return obj.hexdigest()


class MyadminForm(bootstrap.BootstrapForm):
    user_name = forms.CharField(required=True,
                                label="管理员名称",
                                widget=forms.TextInput(attrs={'class': 'form-control', }))
    password = forms.CharField(required=True,label="密码",
                               widget=forms.PasswordInput(attrs={'class': 'form-control', }))

    confirm_pwd = forms.CharField(required=True,label="确认密码",
                                  widget=forms.PasswordInput(attrs={'class': 'form-control', }))

    class Meta:
        model = MyAdmin
        fields = '__all__'

    def clean_confirm_pwd(self):
        pwd = self.cleaned_data.get('password')
        c_pwd = get_md5(self.cleaned_data.get('confirm_pwd'))
        if pwd != c_pwd:
            raise ValidationError("密码不一致")
        return c_pwd

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return get_md5(pwd)


class MyadminFormEdit(bootstrap.BootstrapForm):
    class Meta:
        model = MyAdmin
        fields = ['user_name']  # 这里只传username 防止其他也被不小心更新


class MyadminFormReset(bootstrap.BootstrapForm):
    password = forms.CharField(required=True, label="输入新密码", min_length=8,
                               widget=forms.PasswordInput(attrs={'class': 'form-control', }))
    confirm_pwd = forms.CharField(required=True, label="确认新密码", min_length=8,
                                  widget=forms.PasswordInput(attrs={'class': 'form-control', }))

    class Meta:
        model = MyAdmin
        fields = ["password", "confirm_pwd"]

    def clean_confirm_pwd(self):
        pwd = self.cleaned_data.get('password')
        c_pwd = get_md5(self.cleaned_data.get('confirm_pwd'))
        if pwd != c_pwd:
            raise ValidationError("密码不一致")
        return c_pwd

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return get_md5(pwd)


def myadmin_list(req):
    # info = req.session.get('info')
    # if not info:
    #     return redirect('/login')
    search_data_dict = {}
    search_data = req.GET.get("q", "")  # 如果q没传回东西，则返回“”里内容
    if search_data:
        search_data_dict['user_name_contains'] = search_data
    queryset = MyAdmin.objects.filter(**search_data_dict)
    # 等同于queryset = MyAdmin.objects.filter(user_name_contains=search_data)
    # 后面的_contains指user_name里有符合条件的就选出来，如数据库user_name里有张球球，search_data里有张就选出来
    # return render(req,'myadmin_list.html')
    page_nav_obj = page_nav.PageNav(req, queryset)
    page_queryset = page_nav_obj.page_queryset
    page_nav_string = page_nav_obj.get_html()
    content = {
        "queryset": page_queryset,
        "page_nav_string": page_nav_string,
    }
    return render(req, "myadmin_list.html", content)


def myadmin_add(req):
    if req.method == "GET":
        form = MyadminForm()
        return render(req, "change.html", {"form": form, "add_name": "添加管理员"})
    else:
        form = MyadminForm(req.POST)
        if form.is_valid():
            form.save()
            return redirect('/myadmin/list')
        else:
            return render(req, "change.html", {"form": form})


def myadmin_delete(req):
    nid = req.GET.get('nid')
    MyAdmin.objects.get(id=nid).delete()
    return redirect('/myadmin/list')
    # 想对一个东西做修改又不想跳转新网页可以这样
    # 超链接里取号 然后删除 GET.get就是从href链接里取nid=“”里的内容
    # url里带问号 如?nid={{ obj.id }} 会当做req的一部分传给req


def myadmin_edit(req,nid):
    row_obj = MyAdmin.objects.get(id=nid)  # 先通过href链接查询目标
    if not row_obj:
        return render(req,"error.html")
        # /myadmin/{{ obj.id }}/reset 这是前端写法
        # myadmin/<int:nid>/reset/ 这是url写法 GET可以从url获取参数
    if req.method == "GET":
        form = MyadminFormEdit(instance=row_obj)  # 把数据库里的值传给表单
        return render(req,"change.html", {"form": form, "title": "编辑管理员"})
    # 通过修改键 进入change页面 这里的change页面已经通过href链接获取里数据库目标  并传给里了change页面
    else:
        form = MyadminFormEdit(instance=row_obj, data=req.POST)  # 绑定数据并更新
        # 把用户提交的表单数据（req.POST）更新到数据库中的 row_obj 这条记录里
        if form.is_valid():
            form.save()  # 保存更新过的数据，而不是新增
            return redirect('/myadmin/list')
        return render(req, "change.html", {"form": form})
def myadmin_reset_pwd(req, nid):
    row_obj = MyAdmin.objects.filter(id=nid).first()
    if not row_obj:
        return render(req,"error.html")

    if req.method == "GET":
        form = MyadminFormReset(instance=row_obj)  # 将数据库内容传给form表单
        return render(req, "change.html", {"form": form})
    else:
        form = MyadminFormReset(instance=row_obj, data=req.POST)
        if form.is_valid():
            form.save()
            return redirect('/myadmin/list')
        return render(req, "change.html", {"form": form})


